<script setup>
import { message } from "ant-design-vue";
import { ref, onMounted, watch } from "vue";
import { getProductList, deleteProduct } from "@/service/services.js";
import axios from "axios";
import { useRouter } from "vue-router";
import { useAccountStore } from "@/stores/account.js";
const account = useAccountStore();
const tableHeight = ref(0);
const name = ref("");
const code = ref("");
const fileInput = ref(null);
const open = ref(false);
const data = ref([]);
const id = ref("");
const page = ref(1);
const pageSize = ref(15);
const totals = ref(1);
const pageSizeChange = (current, size) => {
  page.value = current;
  pageSize.value = size;
  getInfo();
};
const pageChange = (current, size) => {
  page.value = current;
  pageSize.value = size;
  getInfo();
};
const pagination = ref({
  // 表格分页的配置
  pageSize,
  current: page,
  total: totals,
  showTotal: (totals) => `共 ${totals} 条`,
  onShowSizeChange: pageSizeChange,
  onChange: pageChange,
});
const columns = [
  {
    title: "操作",
    key: "operation",
    fixed: "left",
    width: 180,
  },
  {
    title: "产品编码",
    dataIndex: "code",
    key: "code",
  },

  {
    title: "产品名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "材料类别",
    dataIndex: "type",
    key: "type",
  },
  {
    title: "规格型号",
    dataIndex: "var1",
    key: "var1",
  },
  {
    title: "单位",
    dataIndex: "var2",
    key: "var2",
  },
  // {
  // 	title: '单户用量',
  // 	dataIndex: 'var3',
  // 	key: 'var3'
  // },
  // {
  // 	title: '单层用量',
  // 	dataIndex: 'var4',
  // 	key: 'var4'
  // },
  // {
  // 	title: '首层用量',
  // 	dataIndex: 'var5',
  // 	key: 'var5'
  // },
  // {
  // 	title: '层数',
  // 	dataIndex: 'var6',
  // 	key: 'var6'
  // },
  // {
  // 	title: '公式',
  // 	dataIndex: 'var7',
  // 	key: 'var7'
  // },
  {
  	title: '单价',
  	dataIndex: 'price',
  	key: 'price'
  },
  {
    title: "总用量",
    dataIndex: "total",
    key: "total",
  },
  {
    title: "供应商名称",
    dataIndex: "companyName",
    key: "companyName",
  },
  {
    title: "产品所属项目名称",
    dataIndex: "programName",
    key: "programName",
  },
  // {
  // 	title: '预警值',
  // 	dataIndex: 'warningValue',
  // 	key: 'warningValue'
  // },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
  },
];
const router = useRouter();

const getInfo = () => {
  account.spinning = true;
  getProductList({
    name: name.value,
    code: code.value,
    pageNum: page.value,
    pageSize: pageSize.value,
  })
    .then((res) => {
      data.value = res.list;
      totals.value = res.total;
      account.spinning = false;
    })
    .catch((err) => {
      account.spinning = false;
      message.error(err);
    });
};
onMounted(() => {
  tableHeight.value = document.getElementById("main").offsetHeight - 220;
  getInfo();
});
watch(
  () => account.currentPrograme,
  (_val, oldVal) => {
    getInfo();
  },
);
const onSearch = () => {
  getInfo();
};
const del = (i) => {
  id.value = i.id;
  open.value = true;
};
const handleOk = () => {
  account.spinning = true;
  deleteProduct({ id: id.value })
    .then((res) => {
      open.value = false;
      getInfo();
    })
    .catch((err) => {
      message.error(err);
    });
};
const edit = (i) => {
  console.log(i);
  router.push({ path: "/main/product/edit", query: i });
};
const add = () => {
  router.push({ path: "/main/product/edit" });
};
const exportFile = () => {
  window.location.href = `${
    window.origin
  }/services/product/export?token=${sessionStorage.getItem("token")}&name=${
    name.value
  }&code=${code.value}`;
};
const importFile = () => {
  fileInput.value.click();
};
const handleFileChange = (event) => {
  const file = event.target.files[0];
  const formData = new FormData();
  formData.append("file", file);
  account.spinning = true;
	event.target.value = '';

  try {
    axios
      .post(`${window.origin}/services/product/import`, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          token: sessionStorage.getItem("token"),
        },
      })
      .then((response) => {
        account.spinning = false;
        if (response.data.code === "401") {
          window.location.replace("/");
        } else if (response.data.code === "500") {
          message.error(response.data.message);
        } else {
          getInfo();
        }
        console.log("Success:", response.data);
      })
      .catch((error) => {
        account.spinning = false;
        message.error(error);
      });
  } catch (error) {
    account.spinning = false;
    message.error(error);
  }
};
</script>

<template>
  <section class="operation">
    <section class="search">
      <a-input
        v-model:value="name"
        placeholder="请输入产品名称"
        @pressEnter="onSearch"
      />
      <a-input
        v-model:value="code"
        placeholder="请输入产品编码"
        @pressEnter="onSearch"
        :style="{ marginLeft: '10px' }"
      />
    </section>
    <section>
      <a-button type="primary" @click="onSearch">查询</a-button>
      <a-button
        type="primary"
        @click="add"
        :style="{ marginLeft: '10px' }"
        >新增</a-button
      >
      <a-button
        type="primary"
        :style="{ marginLeft: '10px', marginRight: '10px' }"
        @click="importFile"
        >导入</a-button
      >
      <input
        type="file"
        ref="fileInput"
        style="display: none"
        @change="handleFileChange"
      />
      <a-button type="primary" @click="exportFile">导出</a-button>
    </section>
  </section>
  <a-table
    :columns="columns"
    :data-source="data"
    :pagination="pagination"
    :scroll="{ y: tableHeight }"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'operation'">
        <section class="col">
          <a-button
            type="primary"
            ghost
            :style="{ marginRight: '10px' }"
            @click="edit(record)"
            :disabled="account.level === '3'"
            >修改</a-button
          >
          <a-button
            type="primary"
            danger
            ghost
            @click="del(record)"
            :disabled="account.level === '3'"
            >删除</a-button
          >
        </section>
      </template>
    </template>
  </a-table>
  <a-modal
    v-model:open="open"
    title="删除"
    centered
    @ok="handleOk"
    @cancel="open = false"
    okText="确认"
    cancelText="取消"
    :closable="false"
    :keyboard="false"
    :maskClosable="false"
  >
    <p>确认删除该条数据？</p>
  </a-modal>
</template>

<style scoped>
.search {
  display: flex;
}
.operation {
  display: flex;
  align-content: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
.col {
  display: flex;
  align-content: center;
  justify-content: space-between;
}
</style>
